<template>
    <el-dialog v-model="visible" draggable title="分配数据权限" destroyOnClose width="600px" @close="closeModal" append-to-body>
        <el-form :model="form" label-width="80px">
            <el-form-item label="角色名称">
                <el-input v-model="form.roleName" :disabled="true" />
            </el-form-item>
            <el-form-item label="权限字符">
                <el-input v-model="form.roleKey" :disabled="true" />
            </el-form-item>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="权限范围" :span="12">
                        <el-select v-model="form.dataScope" @change="dataScopeSelectChange">
                            <el-option v-for="item in dataScopeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item>
                        <el-checkbox v-model="form.customCondition" label="自定义条件" name="type" :true-label="true" :false-label="false" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="数据权限" v-show="form.dataScope == 2">
                <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开/折叠</el-checkbox>
                <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选/全不选</el-checkbox>
                <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
                <el-tree class="tree-border" :data="deptOptions" show-checkbox default-expand-all ref="deptRef" node-key="id" :check-strictly="!form.deptCheckStrictly" empty-text="加载中，请稍候" :props="{ label: 'label', children: 'children' }"></el-tree>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts">
    import { defineComponent, ref, watch, nextTick, reactive, toRefs, getCurrentInstance } from "vue";
    import { dataScope } from "@/api/system/role";
    export default defineComponent({
        props: {
            modelValue: { type: Boolean, default: () => false },
            record: { type: Object, default: () => {} },
        },
        emits: ["update:modelValue", "close"],
        setup(props, { emit }) {
            const visible = ref<Boolean>(props.modelValue);
            const editorValue = ref();
            const { proxy } = getCurrentInstance() as any;
            const deptExpand = ref(true);
            const deptNodeAll = ref(false);
            const deptOptions = ref([]);
            const deptRef = ref<any>();
            /** 数据范围选项*/
            const dataScopeOptions = ref([
                { value: "1", label: "全部数据权限" },
                { value: "2", label: "自定数据权限" },
                { value: "3", label: "本部门数据权限" },
                { value: "4", label: "本部门及以下数据权限" },
                { value: "5", label: "仅本人数据权限" },
                { value: "6", label: "自定义条件" },
            ]);
            const data: any = reactive({
                form: {},
            });
            const { form } = toRefs(data);
            watch(
                () => props.modelValue,
                (value: Boolean) => {
                    visible.value = value;
                    if (value) {
                        openModal();
                        nextTick(() => {
                            handleOpenDataScope();
                        });
                    }
                },
                { immediate: true }
            );
            //    打开弹窗
            const openModal = () => {
                if (!visible.value) {
                    emit("update:modelValue", true);
                }
                return nextTick();
            };
            // 关闭弹窗
            const closeModal = async (type: string = "cancel", data: object = {}) => {
                if (visible.value) {
                    visible.value = false;
                    emit("update:modelValue", false);
                    emit("close", { type: type, data: data });
                }
                return nextTick();
            };

            // 取消
            const cancel = () => {
                closeModal();
            };
            /** 所有部门节点数据 */
            function getDeptAllCheckedKeys() {
                // 目前被选中的部门节点
                let checkedKeys = deptRef.value?.getCheckedKeys();
                // 半选中的部门节点
                let halfCheckedKeys = deptRef.value?.getHalfCheckedKeys();
                checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys!);
                return checkedKeys;
            }
            /** 重置新增的表单以及其他数据  */
            function reset() {
                deptExpand.value = true;
                deptNodeAll.value = false;
                form.value = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: 0,
                    status: "0",
                    deptIds: [],
                    deptCheckStrictly: true,
                    remark: undefined,
                    customStatement: undefined,
                };
            }
            /** 树权限（展开/折叠）*/
            function handleCheckedTreeExpand(value: any, type: any) {
                let treeList: any = deptOptions.value;
                for (let i = 0; i < treeList.length; i++) {
                    deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
                }
            }
            /** 树权限（全选/全不选） */
            function handleCheckedTreeNodeAll(value: any, type: any) {
                deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
            }
            /** 树权限（父子联动） */
            function handleCheckedTreeConnect(value: any, type: any) {
                form.value.deptCheckStrictly = value ? true : false;
            }
            /** 分配数据权限操作 */
            function handleOpenDataScope() {
                form.value = props.record?.form;

                props.record?.deptTreeSelect.then((res: any) => {
                    deptOptions.value = res.depts;
                    nextTick(() => {
                        if (deptRef.value) {
                            deptRef.value.setCheckedKeys(res.checkedKeys);
                        }
                    });
                });
            }
            /** 选择角色权限范围触发 */
            function dataScopeSelectChange(value: any) {
                if (value !== "2") {
                    deptRef.value.setCheckedKeys([]);
                }
            }

            /** 提交按钮 */
            function submitForm() {
                if (form.value.roleId != undefined) {
                    form.value.deptIds = getDeptAllCheckedKeys();
                    dataScope(form.value).then((response) => {
                        proxy.$modal.msgSuccess("修改成功");
                        closeModal("submit", form.value);
                    });
                }
            }

            return {
                visible,
                cancel,
                closeModal,
                openModal,
                editorValue,
                form,
                deptExpand,
                deptNodeAll,
                deptOptions,
                deptRef,
                handleCheckedTreeExpand,
                handleCheckedTreeNodeAll,
                handleCheckedTreeConnect,
                submitForm,
                dataScopeSelectChange,
                dataScopeOptions,
            };
        },
    });
</script>

<style scoped lang="scss">
    :deep(.el-dialog:not(.is-fullscreen)) {
        margin-top: 0 !important;
    }
</style>
